<?php

namespace app\admin\controller\financing;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Env;

/**
 * 补缴诊疗收费
 *
 * @icon fa fa-user
 */
class Supplementary extends Backend
{


    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        //$this->model = new \app\admin\model\Registration;
        $this->model = new \app\admin\model\Accepts;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["users"=>['id','name'],"medic"=>['id','name'],"info"=>['id','name']])
                //->with(["info"=>['id','name','sex','birthday']])
                ->with([
                    'info' => function ($query) {
                        $query->withField('id,name,sex,birthday');
                    }
                ])
                ->where($where)
                ->where('on_credit','<>',0)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    //1代表转账，2代表现金，3代表pos机，4代表支付宝，5代表微信，6代表储值卡，7代表积分
                    switch ($v->pays){
                        case 1:
                            $list->items()[$k]->pays = '转账';
                            break;
                        case 2:
                            $list->items()[$k]->pays = '现金';
                            break;
                        case 3:
                            $list->items()[$k]->pays = 'pos机';
                            break;
                        case 4:
                            $list->items()[$k]->pays = '支付宝';
                            break;
                        case 5:
                            $list->items()[$k]->pays = '微信';
                            break;
                        case 6:
                            $list->items()[$k]->pays = '储值卡';
                            break;
                        case 7:
                            $list->items()[$k]->pays = '积分';
                            break;
                        default:
                            $list->items()[$k]->pays = '无';
                            break;
                    }


                    $list->items()[$k]->age = countage($v->info['birthday']);
                    $list->items()[$k]->receivable = number_format($v->count_cost+$v->other_cost-$v->vip_discounts-$v->iscounts_cost-$v->vip_deduction+($v->new_price),2,'.','');
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



//    /**
//     * 编辑
//     */
//    public function edit($ids = null)
//    {
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds)) {
//            if (!in_array($row[$this->dataLimitField], $adminIds)) {
//                $this->error(__('You have no permission'));
//            }
//        }
//        if ($this->request->isPost()) {
//            $params = $this->request->post("row/a");
//
//
//            if ($params['on_account'] > $params['supplementary']){
//                $this->error('赊账金额不能大于补交金额');
//            }
//
//            $params['payees'] = $this->auth->nickname;
//            $params['on_credit'] = 2;
//            $params['status'] = 2;
//            $params['reality_cost'] = $row->reality_cost+$params['supplementary'];
//            unset($params['on_account']);
//
//            $order_arr = Db::table('fa_diagnosis_order')
//                ->where('id',$params['id'])
//                ->find();
//
//            $users_arr = Db::table('fa_diagnosis_order')
//                ->alias('a')
//                ->field('a.info_id,b.user_id,c.level,c.vip,c.money')
//                ->join('fa_info b','a.info_id=b.id')
//                ->join('fa_users c','b.user_id=c.id')
//                ->where('a.id',$params['id'])
//                ->find();
//
//
//            if ($params) {
//                $params = $this->preExcludeFields($params);
//                $result = false;
//                Db::startTrans();
//                try {
//                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
//                        $row->validateFailException(true)->validate($validate);
//                    }
//
//                    if ($params['pays'] == 6){
//                        $pays = $users_arr['money'] - $params['supplementary'];
//                        if ($pays < 0){
//                            //事务回滚
//                            Db::rollback();
//                            $this->error('储值卡余额不足');
//                        }
//
//                        $dec = Db::table('fa_users')
//                            ->where('id',$users_arr['user_id'])
//                            ->setDec('money',$params['supplementary']);
//
//                        $log = Db::table('fa_card_log')
//                            ->insertGetId([
//                                'user_id' => $users_arr['user_id'],
//                                'money' => $params['supplementary'],
//                                'create_time' => time(),
//                                'info_id' => $order_arr['info_id'],
//                                'type' => 2,
//                            ]);
//                    }else{
//                        $dec = 1;
//                        $log = 1;
//                    }
//
//
//                    if ($params['pays'] == 7){
//                        $pid_arr = Db::table('fa_users')
//                            ->where('id',$users_arr['user_id'])
//                            ->find();
//
//                        $integral =  floor($params['supplementary']/10);
//
//                        if (empty($pid_arr)){
//                            //事务回滚
//                            Db::rollback();
//                            $this->error('该账户数据为空');
//                        }
//
//                        $pays = $pid_arr['integral'] - $params['supplementary'];
//                        if ($pays < 0){
//                            //事务回滚
//                            Db::rollback();
//                            $this->error('积分不足');
//                        }
//
//                        $decs = Db::table('fa_users')
//                            ->where('id',$users_arr['user_id'])
//                            ->setDec('integral',$params['supplementary']);
//
//                        $logs = Db::table('fa_integral_log')
//                            ->insertGetId([
//                                'user_id' => $users_arr['user_id'],
//                                'info_id' => $users_arr['info_id'],
//                                'integral' => $params['supplementary'],
//                                'create_time' => time(),
//                                'type' => 1,
//                                'way' => 1,
//                            ]);
//
//                        //加积分
//                        if (!empty($pid_arr['invite'])){
//                            $decss = Db::table('fa_users')
//                                ->where('id',$pid_arr['invite'])
//                                ->setInc('integral',$integral);
//
//                            $logss = Db::table('fa_integral_log')
//                                ->insertGetId([
//                                    'user_id' => $pid_arr['invite'],
//                                    'info_id' => $users_arr['info_id'],
//                                    'integral' => $integral,
//                                    'create_time' => time(),
//                                    'type' => 2,
//                                    'way' => 1,
//                                ]);
//                        }else{
//                            $decss = 1;
//                            $logss = 1;
//                        }
//
//                    }else{
//                        $decs = 1;
//                        $logs = 1;
//                        $decss = 1;
//                        $logss = 1;
//                    }
//
////                    if ($params['pays'] != 7){
////                        $user_arr = Db::table('fa_users')
////                            ->where('id',$users_arr['user_id'])
////                            ->find();
////                        //大客户加日志
////                        if (!empty($user_arr['big_id'])){
////                            $big_arr = Db::table('fa_big')
////                                ->where('id',$user_arr['big_id'])
////                                ->find();
////
////                            $year = intval(date('Y'));
////                            $month = intval(date('m'));
////                            $moneys = number_format($params['supplementary'],2,'.','');
////
////                            $big_log = Db::table('fa_big_log')
////                                ->insertGetId([
////                                    'big_id' => $user_arr['big_id'],
////                                    'info_id' => $order_arr['info_id'],
////                                    'code' => $order_arr['code'],
////                                    'date' => date('Y-m-d'),
////                                    'money' => $moneys,
////                                    'create_time' => time(),
////                                    'type' => 2,
////                                ]);
////
////                            $pan_arr = Db::table('fa_big_data')
////                                ->where(['big_id'=>$user_arr['big_id'],'year'=>$year,'month'=>$month])
////                                ->find();
////
////                            if (empty($pan_arr)){
////                                $insert_data = Db::table('fa_big_data')
////                                    ->insertGetId([
////                                        'big_id' => $user_arr['big_id'],
////                                        'year' => $year,
////                                        'month' => $month,
////                                        'money' => $moneys,
////                                        'create_time' => time(),
////                                    ]);
////                            }else{
////                                $insert_data = Db::table('fa_big_data')
////                                    ->where('id',$pan_arr['id'])
////                                    ->update([
////                                        'money' => number_format($pan_arr['money']+$moneys,2,'.',''),
////                                        'update_time' => time(),
////                                    ]);
////                            }
////
////
////                            if ($big_arr['pid'] != 0){
////                                $pid_money = number_format($params['supplementary']*0.05,2,'.','');
////                                $big_logs = Db::table('fa_big_logs')
////                                    ->insertGetId([
////                                        'big_id' => $big_arr['pid'],
////                                        'code' => $order_arr['code'],
////                                        'date' => date('Y-m-d'),
////                                        'moneys' => $pid_money,
////                                        'type' => 2,
////                                        'create_time' => time(),
////                                    ]);
////
////                                $pan_arrs = Db::table('fa_big_data')
////                                    ->where(['big_id'=>$big_arr['pid'],'year'=>$year,'month'=>$month])
////                                    ->find();
////
////                                if (empty($pan_arrs)){
////                                    $insert_datas = Db::table('fa_big_data')
////                                        ->insertGetId([
////                                            'big_id' => $big_arr['pid'],
////                                            'year' => $year,
////                                            'month' => $month,
////                                            'money' => $pid_money,
////                                            'create_time' => time(),
////                                        ]);
////                                }else{
////                                    $insert_datas = Db::table('fa_big_data')
////                                        ->where('id',$pan_arrs['id'])
////                                        ->update([
////                                            'money' => number_format($pan_arrs['money']+$pid_money,2,'.',''),
////                                            'update_time' => time(),
////                                        ]);
////                                }
////                            }else{
////                                $big_logs = 1;
////                                $insert_datas = 1;
////                            }
////
////                            if ($big_arr['ppid'] != 0){
////                                $ppid_money = number_format($params['supplementary']*0.03,2,'.','');
////                                $big_logss = Db::table('fa_big_logs')
////                                    ->insertGetId([
////                                        'big_id' => $big_arr['ppid'],
////                                        'code' => $order_arr['code'],
////                                        'date' => date('Y-m-d'),
////                                        'moneys' => $ppid_money,
////                                        'type' => 2,
////                                        'create_time' => time(),
////                                    ]);
////
////                                $pan_arrss = Db::table('fa_big_data')
////                                    ->where(['big_id'=>$big_arr['ppid'],'year'=>$year,'month'=>$month])
////                                    ->find();
////
////                                if (empty($pan_arrss)){
////                                    $insert_datass = Db::table('fa_big_data')
////                                        ->insertGetId([
////                                            'big_id' => $big_arr['ppid'],
////                                            'year' => $year,
////                                            'month' => $month,
////                                            'money' => $ppid_money,
////                                            'create_time' => time(),
////                                        ]);
////                                }else{
////                                    $insert_datass = Db::table('fa_big_data')
////                                        ->where('id',$pan_arrss['id'])
////                                        ->update([
////                                            'money' => number_format($pan_arrss['money']+$ppid_money,2,'.',''),
////                                            'update_time' => time(),
////                                        ]);
////                                }
////
////                            }else{
////                                $big_logss = 1;
////                                $insert_datass = 1;
////                            }
////
////
////                        }else{
////                            $big_log = 1;
////                            $big_logs = 1;
////                            $big_logss = 1;
////                            $insert_data = 1;
////                            $insert_datas = 1;
////                            $insert_datass = 1;
////                        }
////                    }else{
////                        $big_log = 1;
////                        $big_logs = 1;
////                        $big_logss = 1;
////                        $insert_data = 1;
////                        $insert_datas = 1;
////                        $insert_datass = 1;
////                    }
//
//
//
//                    $result = $row->allowField(true)->save($params);
//
//
//
//                } catch (ValidateException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (PDOException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (Exception $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                }
//                if (($result !== false) && ($dec !== false) && ($log !== false) && ($decs !== false) && ($logs !== false) && ($decss !== false) && ($logss !== false)) {
//                    Db::commit();
//                    $this->success();
//                } else {
//                    Db::rollback();
//                    $this->error(__('No rows were updated'));
//                }
//            }
//            $this->error(__('Parameter %s can not be empty', ''));
//        }
//        $this->view->assign("row", $row);
//        return $this->view->fetch();
//    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $order_arr = Db::table('fa_diagnosis_order')
                ->where('id',$params['id'])
                ->find();

            $users_arr = Db::table('fa_diagnosis_order')
                ->alias('a')
                ->field('a.info_id,b.user_id,c.level,c.vip,c.money')
                ->join('fa_info b','a.info_id=b.id')
                ->join('fa_users c','b.user_id=c.id')
                ->where('a.id',$params['id'])
                ->find();


            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if ($params['on_account'] > $params['supplementary']){

                        if ($params['supplementary'] <= 0){
                            $this->error('补缴金额不能小于等于0');
                        }
                    }else{
                        $params['on_credit'] = 2;
                        $params['status'] = 2;
                    }

                    $params['on_account'] = $params['on_account']-$params['supplementary'];
                    $params['payees'] = $this->auth->nickname;
                    $params['reality_cost'] = $row->reality_cost+$params['supplementary'];
                    //unset($params['on_account']);

                    if ($params['pays'] == 6){
                        $pays = $users_arr['money'] - $params['supplementary'];
                        if ($pays < 0){
                            //事务回滚
                            Db::rollback();
                            $this->error('储值卡余额不足');
                        }

                        $dec = Db::table('fa_users')
                            ->where('id',$users_arr['user_id'])
                            ->setDec('money',$params['supplementary']);

                        $log = Db::table('fa_card_log')
                            ->insertGetId([
                                'user_id' => $users_arr['user_id'],
                                'money' => $params['supplementary'],
                                'create_time' => time(),
                                'info_id' => $order_arr['info_id'],
                                'type' => 2,
                            ]);
                    }else{
                        $dec = 1;
                        $log = 1;
                    }


                    $debt_log = Db::table('fa_debt_log')
                        ->insertGetId([
                            'order_id' => $params['id'],
                            'admin_id' => $this->auth->id,
                            'pays' => $params['pays'],
                            'money' => $params['supplementary'],
                            'create_time' => time(),
                        ]);

                    $result = $row->allowField(true)->save($params);




                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if (($result !== false) && ($dec !== false) && ($log !== false) && ($debt_log !== false)) {
                    Db::commit();
                    $this->success();
                } else {
                    Db::rollback();
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



}
